﻿using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using Polly;
using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using WMSSystem.YSL.Dto.SignaIR;
using WMSSystem.YSL.Interfance;

namespace WMSSystem.Web.Hubs
{

    /// <summary>
    /// 实时统计数据SignalR Hub
    /// </summary>
    public class RealTimeStatisticsHub : Hub
    {
        private readonly ILogger<RealTimeStatisticsHub> _logger;
        private readonly IRealTimeStatisticsService _statisticsService;

        public RealTimeStatisticsHub(
            ILogger<RealTimeStatisticsHub> logger,
            IRealTimeStatisticsService statisticsService)
        {
            _logger = logger;
            _statisticsService = statisticsService;
        }

        public override async Task OnConnectedAsync()
        {
            _logger.LogInformation($"客户端 {Context.ConnectionId} 已连接到实时统计Hub");
            // 连接时推送一次数据
            var input = new GetRealTimeStatisticsInputDto { Year = DateTime.Now.Year };
            var statistics = await _statisticsService.GetRealTimeStatisticsAsync(input);
            await Clients.Caller.SendAsync("ReceiveRealTimeStatistics", statistics);
            await base.OnConnectedAsync();
        }

        public override async Task OnDisconnectedAsync(Exception? exception)
        {
            _logger.LogInformation($"客户端 {Context.ConnectionId} 已断开连接");
            await base.OnDisconnectedAsync(exception);
        }

        public async Task RequestRealTimeStatistics(GetRealTimeStatisticsInputDto input)
        {
            var statistics = await _statisticsService.GetRealTimeStatisticsAsync(input);
            await Clients.Caller.SendAsync("ReceiveRealTimeStatistics", statistics);
        }
    }
}
